<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="物料编码" prop="itemNum">
        <el-input clearable @keyup.enter.native="handleQuery"
                  v-model="queryParams.itemNum" placeholder="请输入物料编码模糊查询"/>
      </el-form-item>

      <el-form-item label="仓库id" prop="fkStockUuid">
        <el-input
          v-model="queryParams.fkStockUuid"
          placeholder="请输入仓库id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓位id" prop="fkStockPosUuid">
        <el-input
          v-model="queryParams.fkStockPosUuid"
          placeholder="请输入仓位id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计量单位" prop="wmsDictMeasuringUnit">
        <el-select v-model="queryParams.wmsDictMeasuringUnit" placeholder="请选择计量单位" clearable size="small">
          <el-option
            v-for="dict in dict.type.wms_dict_measuring_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="更新时间">
        <el-date-picker
          v-model="daterangeUpdateAt"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:inventory:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:inventory:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:inventory:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wms:inventory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料编码" align="center" prop="itemNum" />
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="itemSpecification" />
      <el-table-column label="仓库" align="center" prop="stockName" />
      <el-table-column label="仓位" align="center" prop="stockPosName" />
      <el-table-column label="计量单位" align="center" prop="measuringUnit" />
      <el-table-column label="库存数量" align="center" prop="inventoryQty" />
      <el-table-column label="更新时间" align="center" prop="updateAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="inventoryNote" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:inventory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:inventory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="仓库" prop="fkStockUuid">
          <el-select v-model="form.fkStockUuid" placeholder="请选择仓库" style="width: 100%;">
            <el-option
              v-for="data in stocks"
              :key="data.stockUuid"
              :label="data.stockName"
              :value="data.stockUuid"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="仓位" prop="fkStockPosUuid">
          <el-select v-model="form.fkStockPosUuid" placeholder="请选择仓位" style="width: 100%;" filterable>
            <el-option
              v-for="data in stockPositions"
              :key="data.stockPosUuid"
              :label="data.stockPosName"
              :value="data.stockPosUuid"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="物料" prop="fkItemUuid">
          <el-input v-model="form.fkItemUuid" v-show="false"/>
          <el-input placeholder="请选择" readOnly="true" v-model="form.itemName"
                    class="input-with-select">
            <el-tooltip content="点击选择物料" slot="append" placement="right-start" >
              <el-button @click="showDialog_selectItem" icon="el-icon-search"></el-button>
            </el-tooltip>
          </el-input>
        </el-form-item>

<!--        库存数量-->
        <el-form-item label="库存数量" prop="inventoryQty">
          <el-input v-model="form.inventoryQty" placeholder="请输入库存数量">
            <el-tooltip content="选择物料后，带出计量单位。" placement="right-start" slot="append">
              <el-button>{{form.measuringUnit}}</el-button>
            </el-tooltip>
          </el-input>
        </el-form-item>

        <el-form-item label="更新时间" prop="updateAt">
          <el-date-picker clearable size="small" style="width: 100%;"
            v-model="form.updateAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="inventoryNote">
          <el-input v-model="form.inventoryNote" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <select-item ref="component_selectItem" @ok="selectItem_done"/>

  </div>
</template>

<script>
import { listInventory, getInventory, delInventory, addInventory, updateInventory } from "@/api/wms/inventory";
import { listStock } from "@/api/wms/stock"
import { listStockPosition } from "@/api/wms/stockPosition"
import selectItem from "../../wms/wmsItems/selectItem";
import  { getNowTime } from '@/utils/date-time'  // 引入

export default {
  name: "Inventory",
  dicts: ['wms_dict_measuring_unit'],
  components: {selectItem},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存表格数据
      inventoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeUpdateAt: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fkStockUuid: null,
        fkStockPosUuid: null,
        wmsDictMeasuringUnit: null,
        updateAt: null,
        inventoryNote: null
      },
      // 表单参数
      form: {
        fkItemUuid: '',
        itemName: ''
      },
      // 表单校验
      rules: {
        fkStockUuid: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        fkStockPosUuid: [
          { required: true, message: "仓位不能为空", trigger: "blur" }
        ],
        fkItemUuid: [
          { required: true, message: "物料不能为空", trigger: "blur" }
        ],
        inventoryQty: [
          { required: true, message: "库存数量不能为空", trigger: "blur" }
        ],
        wmsDictMeasuringUnit: [
          { required: true, message: "计量单位不能为空", trigger: "change" }
        ],
        updateAt: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
      },

      stocks:[],
      stockPositions:[],


    };
  },
  created() {
    this.getList();

    listStock({}).then(response => {
      console.log(response)
      this.stocks = response.rows
    })

    listStockPosition({}).then(response => {
      console.log(response)
      this.stockPositions = response.rows
      console.log(response.rows[0])
    })

  },
  methods: {
    /** 查询库存列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeUpdateAt && '' != this.daterangeUpdateAt) {
        this.queryParams.params["beginUpdateAt"] = this.daterangeUpdateAt[0];
        this.queryParams.params["endUpdateAt"] = this.daterangeUpdateAt[1];
      }
      listInventory(this.queryParams).then(response => {
        this.inventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inventoryUuid: null,
        fkStockUuid: null,
        fkStockPosUuid: this.stockPositions[0].stockPosUuid,
        fkItemUuid: null,
        measuringUnit: '❓',
        inventoryQty: null,
        wmsDictMeasuringUnit: null,
        recentlyDocNum: null,
        updateAt: getNowTime(),
        inventoryNote: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeUpdateAt = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inventoryUuid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库存";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const inventoryUuid = row.inventoryUuid || this.ids
      getInventory(inventoryUuid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库存";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.inventoryUuid != null) {
            updateInventory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const inventoryUuids = row.inventoryUuid || this.ids;
      this.$modal.confirm('是否确认删除库存编号为"' + inventoryUuids + '"的数据项？').then(function() {
        return delInventory(inventoryUuids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/inventory/export', {
        ...this.queryParams
      }, `wms_inventory.xlsx`)
    },

    /** 打开选择物料弹窗 */
    showDialog_selectItem() {
      console.log('showDialog_selectItem')
      this.$refs.component_selectItem.show();
    },

    /** 选择物料完成 */
    selectItem_done(m) {
      this.form.fkItemUuid = m.itemUuid
      this.form.measuringUnit = m.measuringUnitLabel
      this.form.itemName = `${m.itemName} ${m.itemSpecification}（${m.itemNum}）`
      // this.$refs["form"].validate() // 重新校验表单
    },

  }
};
</script>
